const express = require('express');
const router = express.Router();
const multer = require('multer');
const faceapi = require('face-api.js');
const canvas = require('canvas');
const path = require('path');
const fs = require('fs');

// 配置multer存储
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    const uploadDir = path.join(__dirname, 'uploads');
    if (!fs.existsSync(uploadDir)) {
      fs.mkdirSync(uploadDir, { recursive: true });
    }
    cb(null, uploadDir);
  },
  filename: function (req, file, cb) {
    cb(null, Date.now() + path.extname(file.originalname));
  }
});

const upload = multer({ storage: storage });

// 配置face-api.js
const { Canvas, Image, ImageData } = canvas;
faceapi.env.monkeyPatch({ Canvas, Image, ImageData });

// 加载模型
const MODEL_URL = path.join(__dirname, 'models');
let modelsLoaded = false;

async function loadModels() {
  if (!modelsLoaded) {
    try {
      await faceapi.nets.ssdMobilenetv1.loadFromDisk(MODEL_URL);
      await faceapi.nets.faceLandmark68Net.loadFromDisk(MODEL_URL);
      await faceapi.nets.faceRecognitionNet.loadFromDisk(MODEL_URL);
      modelsLoaded = true;
      console.log('人脸识别模型加载成功');
    } catch (error) {
      console.error('模型加载失败:', error);
      throw error;
    }
  }
}

// 初始化模型
loadModels().catch(console.error);

// 确保face-data目录存在
const faceDataDir = path.join(__dirname, 'face-data');
if (!fs.existsSync(faceDataDir)) {
  fs.mkdirSync(faceDataDir, { recursive: true });
}

// 人脸注册API
router.post('/register', upload.single('image'), async (req, res) => {
  try {
    if (!req.file) {
      return res.status(400).json({ error: '未上传图片' });
    }

    const { userId } = req.body;
    if (!userId) {
      return res.status(400).json({ error: '用户ID不能为空' });
    }

    // 读取图片
    const img = await canvas.loadImage(req.file.path);
    
    // 检测人脸
    const detections = await faceapi.detectSingleFace(img)
      .withFaceLandmarks()
      .withFaceDescriptor();

    if (!detections) {
      return res.status(400).json({ error: '未检测到人脸' });
    }

    // 保存人脸特征数据
    const faceData = {
      userId,
      descriptor: Array.from(detections.descriptor),
      timestamp: new Date().toISOString()
    };

    const faceDataFile = path.join(faceDataDir, `${userId}.json`);
    fs.writeFileSync(faceDataFile, JSON.stringify(faceData, null, 2));

    // 删除上传的临时图片
    fs.unlinkSync(req.file.path);

    res.json({ 
      success: true, 
      message: '人脸注册成功',
      userId 
    });
  } catch (error) {
    console.error('人脸注册失败:', error);
    res.status(500).json({ error: '人脸注册失败，请重试' });
  }
});

// 人脸验证API
router.post('/verify', upload.single('image'), async (req, res) => {
  try {
    if (!req.file) {
      return res.status(400).json({ error: '未上传图片' });
    }

    const { userId } = req.body;
    if (!userId) {
      return res.status(400).json({ error: '用户ID不能为空' });
    }

    // 读取注册的人脸特征数据
    const faceDataFile = path.join(faceDataDir, `${userId}.json`);
    if (!fs.existsSync(faceDataFile)) {
      return res.status(404).json({ error: '未找到该用户的人脸数据' });
    }

    const registeredFaceData = JSON.parse(fs.readFileSync(faceDataFile, 'utf8'));
    
    // 读取并检测当前上传的人脸
    const img = await canvas.loadImage(req.file.path);
    const detections = await faceapi.detectSingleFace(img)
      .withFaceLandmarks()
      .withFaceDescriptor();

    if (!detections) {
      return res.status(400).json({ error: '未检测到人脸' });
    }

    // 计算人脸特征的距离（相似度）
    const distance = faceapi.euclideanDistance(
      detections.descriptor,
      new Float32Array(registeredFaceData.descriptor)
    );

    // 设置阈值，小于阈值表示是同一个人
    const threshold = 0.6;
    const isMatch = distance < threshold;

    // 删除上传的临时图片
    fs.unlinkSync(req.file.path);

    res.json({
      success: true,
      isMatch,
      distance,
      threshold,
      message: isMatch ? '人脸验证通过' : '人脸验证失败'
    });
  } catch (error) {
    console.error('人脸验证失败:', error);
    res.status(500).json({ error: '人脸验证失败，请重试' });
  }
});

module.exports = router; 